package com.example.aussiehealthhelper;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
import android.widget.Toast;

public class DrugManagementActivity extends AppCompatActivity implements DrugManageAdapter.DeleteClickListener {

    private HealthDbHelper dbHelper;
    private RecyclerView rvDrugList;
    private FloatingActionButton fabAddDrug;
    private DrugManageAdapter adapter;
    private List<Drug> drugList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drug_management);

        dbHelper = new HealthDbHelper(this);
        rvDrugList = findViewById(R.id.rvDrugList);
        fabAddDrug = findViewById(R.id.fabAddDrug);
        rvDrugList.setLayoutManager(new LinearLayoutManager(this));
        loadDrugs();
        //按钮点击
        fabAddDrug.setOnClickListener(v -> {
            Intent intent = new Intent(this, DrugEditActivity.class);
            startActivity(intent);
        });
    }

    private void loadDrugs() {
        drugList = dbHelper.getAllDrugs();
        adapter = new DrugManageAdapter(this, drugList, this);
        rvDrugList.setAdapter(adapter);
    }

    //实现回调接口
    @Override
    public void onDeleteRequested(Drug drug, int position) {
        //显示删除确认对话框
        new AlertDialog.Builder(this)
                .setTitle("删除药品")
                .setMessage("确定要删除'" + drug.getNameCN() + "'吗？此操作不可撤销。")
                .setPositiveButton("删除", (dialog, which) -> deleteDrug(drug, position))
                .setNegativeButton("取消", null)
                .show();
    }

    //执行删除操作
    private void deleteDrug(Drug drug, int position) {
        int result = dbHelper.deleteDrug(drug.getId());
        if (result > 0) {
            drugList.remove(position);
            adapter.notifyItemRemoved(position);
            adapter.notifyItemRangeChanged(position, drugList.size());

            showToast("'" + drug.getNameCN() + "' 已成功删除");
        } else {
            showToast("删除失败，请重试");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //每次返回时刷新数据
        loadDrugs();
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbHelper != null) {
            dbHelper.close();
        }
    }
}